<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" clearable placeholder="部门名称"></el-input>
				</el-form-item>

				<el-form-item>
					<!--v-model:选择的值装起来
						:lable:下拉框的选项可以看到的值
						:value:
					-->
				<el-select v-model="filters.parentId" clearable placeholder="请选择">
					<el-option
							v-for="item in parentDepts"
							:key="item.id"
							:label="item.name"
							:value="item.id">
					</el-option>
				</el-select>
				</el-form-item>
				<el-form-item>
				<el-select v-model="filters.managerId" clearable placeholder="请选择">
					<el-option
							v-for="item in managers"
							:key="item.id"
							:label="item.username"
							:value="item.id">
					</el-option>
				</el-select>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" v-on:click="getdept(1)">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
<!--		:data :绑定的数据-->
<!--		v-loading: 页面css样式等东西加载之后加载加载数据-->
<!--		prop:对应的是:data绑定的对象的属性-->
<!--		label :描述-->
		<el-table :data="dept" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>
				<template slot-scope="scope">
					<el-button type="text" size="small"
							   :type="scope.row.state ===1?'primary':'danger'"
					>
						{{scope.row.state===1?"启用":"禁用"}}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="100" sortable>
			</el-table-column>

			<el-table-column prop="managerName" label="部门经理" width="100" sortable>
			</el-table-column>

			<el-table-column prop="parentName" label="上级部门" width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			current-change:自带的事件,我当前页发生改变时,就会触发此事件-->
			<el-pagination layout="sizes,prev, pager, next"
						   @size-change="sizeChange"
						   @current-change="handleCurrentChange"
						   :page-sizes="[5, 10, 20, 50]"
						   :page-size="size"
						   :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增/编辑界面-->
		<el-dialog title="操作" :visible.sync="editFormVisible"  :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="" prop="state">
					<el-switch
							style="display: block"
							v-model="state"
							active-color="#13ce66"
							inactive-color="#ff4949"
							active-text="状态:启用"
							inactive-text="状态:禁用">
					</el-switch>
				</el-form-item>
				<el-form-item label="上级部门" prop="state">
					<!--无限极的部门结构
					parentIds:[3,8,10]
					v-model="editForm.parentIds"：选择之后的数据会自动装到这个parentIds里面
					-->
				<el-cascader
						v-model="editForm.parentIds"
						:options="treeDepts"
						:props="{ checkStrictly: true,value:'id',label:'name' }"
						clearable></el-cascader>
				</el-form-item>
				<el-form-item label="部门经理" prop="state">
					<el-select v-model="editForm.managerId" clearable placeholder="部门经理">
						<el-option
								v-for="item in allEmps"
								:key="item.id"
								:label="item.username"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	//import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				/*高级查询参数对象*/
				filters: {
					name: '',
					parentId : null,
					managerId : null
				},
				managers:[],//部门经理们
				parentDepts:[],//上级部门们
				dept: [],
				total: 0,
				page: 1,
				size:5,
				listLoading: false,
				sels: [],//列表选中列
				allEmps:[],//所有的员工

				treeDepts:[],//部门层级结构
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				/*表单的规则*/
				editFormRules: {
					/*name: [
						/!*required: true:必须填，如果你没填提示message,trigger:触发 blur:光标离开时候触发*!/
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
					sn: [
						/!*required: true:必须填，如果你没填提示message,trigger:触发 blur:光标离开时候触发*!/
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					]*/
				},
				//编辑界面数据
				editForm: {
					id:'',
					name: '',
					sn: '',
					parentIds:[]
				},
				state:true,
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				}

			}
		},
		methods: {

			//性别显示转换
			//row 当前行row = user  column当前列
			formatSex: function (row, column) {
				return row.state == 1 ? '正常' : row.state == 0 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				//var 就是当前页的数据
				this.page = val;
				this.getdept(2);
				console.log(111)
			},
			sizeChange(size){
				//	alert(size)
				this.size = size
				this.getdept();
				console.log(222)
			},

			//获取部门列表 数据在哪接口里面/dept/findPage
			getdept(flag) {
				//高级查询查第一页
				//封装的数据
				let para = {
					"token":sessionStorage.getItem("token"),
					//page 就是当前页  size:条数
					page: flag === 1?1:this.page,
					size:this.size,
					//这个是高级查询的条件
					keyword: this.filters.name,
					parentId: this.filters.parentId,
					managerId: this.filters.managerId
				};
				this.listLoading = true;

				console.log(para)
				//发送axios请求获取后端准备的分页接口
				// http://localhost/dept/findPage
				// this.$http:main.js准备好的东西
				this.$http.post("/dept/findPage",para).then(res=>{

					//res:后台返回的数据装在这里面
					console.log(res)
					console.log("--------------------")
					console.log(res.data.total)
					console.log(res.data.list)
					console.log("--------------------")
					this.dept = res.data.list
					this.total = res.data.total

					if (this.total%this.size === 0 && flag !== 2){
						this.page = this.page - 1;
						this.getdept(2)
					}

					this.listLoading = false;
				})
			},
			//删除
			handleDel: function (index, row) {
				console.log(index)
				console.log(row)
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };

					//发送axios请求  localhost/dept/10
					this.$http.delete("/dept/"+row.id).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						//刷新列表
						this.getdept();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				//显示编辑页面的模态框
				this.editFormVisible = true;
				//Object.assign 是拷贝对象 BeanUtil.copyof()
				this.editForm = row;
				// "" null undefind NaN false
				//row.state 1     !!1 = true   1
				//this.state= row.state?true:false
				this.state= !!row.state

				//上级部门回显  row：整行所有的数据
				console.log(row)
				console.log(row.dirPath) // /3/8/10
				//1.拿到dirPath字段数据
				var dirPath = row.dirPath;
				//2.变成 Array : [3,8,10]
				var paths = dirPath.split("/");
				console.log(paths)
				paths = paths.slice(1,paths.length - 1);
				console.log(paths)

				//this.editForm.parentIds = [3,8]
				//js5大原始类型 NUmber String Undefined Null Boolean
				paths = paths.map(Number)
				/*var arr = new Array()
				for (let i = 0; i < paths.length ; i++) {
					arr.push(parseInt(paths[i]))
				}
				console.log(arr)*/

				console.log(paths)
				this.editForm.parentIds = paths


				console.log("当前修改的数据是:"+JSON.stringify(this.editForm))
			},
			//显示新增界面
			handleAdd: function () {
				this.editFormVisible = true;
				this.editForm = {
					name: '',
					sn: ''
				};
				this.state = true
			},
			//提交表单
			editSubmit: function () {
				/*规则验证*/
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							//这里面是获取数据的
							this.editLoading = true;
							//拷贝对象
							let para = Object.assign({}, this.editForm);
								para.state = this.state?1:0;
								this.$http.post("/dept",para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
									console.log(res)
								this.$message({
									message: res.data.success?'提交成功':res.data.message,
									type: res.data.success?'success':"error"
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getdept();
							});
						});
					}
				});
			},

			//复选勾选框的方法
			selsChange: function (sels) {
				console.log(sels)
				this.sels = sels;//一行行数据的array
			},
			//批量删除
			batchRemove: function () {
				console.log(this.sels)
				/*
				两种写法是一样的效果
				var  xxx = this.sels.map(item => item.id)
				--------------------------------------------------------
				var arr = new Array()
				for (let i = 0; i < this.sels.length; i++) {
					arr.push(this.sels[i].id)
				}
*/
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					this.$http.patch("/dept?ids="+ids).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getdept();
					});
				}).catch(() => {

				});
			},
			//获取所有的上级部门
			getParentDepts(){
				//发送axios请求获取后台准备接口数据
				this.$http.get("/dept/findParentDepts").then(res => {
					console.log(res)

					this.parentDepts = res.data.data;
				})

			},
			//获取所有的上级部门
			findManager(){
				//发送axios请求获取后台准备接口数据
				this.$http.get("/emp/findManager").then(res => {
					console.log(res)

					this.managers = res.data.data;
				})

			},
			//获取所有的上级部门
			treeDept(){
				//发送axios请求获取后台准备接口数据
				this.$http.get("/dept/treeDept").then(res => {
					console.log(res)
					this.treeDepts = res.data.data;
				})

			},
			findEmps(){
				//发送axios请求获取后台准备接口数据
				this.$http.get("/emp/findAll").then(res => {
					console.log(res)
					this.allEmps = res.data.data;
				})

			}
		},
		//就是页面已加载完成就会去触发这个mounted
		mounted() {
			//获取分页的部门列表
			this.getdept();
			//获取所有的上级部门
			this.getParentDepts();
			//获取所有的上级部门
			this.findManager();
			//获取部门树
			this.treeDept();
			//获取所有的员工
			this.findEmps();
		}
	}

</script>

<style scoped>

</style>
